package com.runnor.common.websys.system.controller;

import cn.hutool.http.HttpResponse;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.runnor.common.websys.system.entity.ApiResult;
import com.runnor.common.websys.system.entity.SysLog;
import com.runnor.common.websys.system.entity.Sysdict;
import com.runnor.common.websys.system.service.SysLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("api/syslog")
public class SysLogController {

    @Autowired
    SysLogService sysLogService;

    /**
     * 分页查询
     */
    @GetMapping("/page")
    @PreAuthorize("hasAuthority('logs:list')")
    public ResponseEntity page(@RequestParam(defaultValue = "1") Integer current,
                               @RequestParam(defaultValue = "10") Integer size,
                               SysLog sysLog) {

        QueryWrapper<SysLog> queryWrapper = new QueryWrapper<>();

        queryWrapper.select("id,remote_addr,http_method,http_method,http_path,access_time,cost," +
                "user_agent,username,java_method_name,LENGTH(req_param) AS 'req_param',LENGTH(resp_data) as 'resp_data'," +
                "IF(exception IS null,1,0) AS 'exception'");

        queryWrapper.like(StringUtils.hasText(sysLog.getRemoteAddr()), "remote_addr", sysLog.getRemoteAddr())
                .like(StringUtils.hasText(sysLog.getHttpPath()), "http_path", sysLog.getHttpPath())
                .eq(StringUtils.hasText(sysLog.getHttpMethod()), "http_method", sysLog.getHttpMethod())
                .like(StringUtils.hasText(sysLog.getUsername()), "username", sysLog.getUsername())
                .like(StringUtils.hasText(sysLog.getJavaMethodName()), "java_method_name", sysLog.getJavaMethodName())
                .isNull(StringUtils.hasText(sysLog.getException()) && "1".equals(sysLog.getException()), "exception")
                .isNotNull(StringUtils.hasText(sysLog.getException()) && "0".equals(sysLog.getException()), "exception")
        ;

        if (sysLog.getDate() != null) {
            List<String> list = Arrays.asList(sysLog.getDate());
            queryWrapper.between("date(access_time)", list.get(0), list.get(1));
        }

        queryWrapper.orderByDesc("access_time");

        Page data = sysLogService.page(new Page(current, size), queryWrapper);
        return ResponseEntity.ok(ApiResult.ok(data));
    }


    /**
     * 根据 id 查询日志记录
     */
    @GetMapping("/getById")
    public ResponseEntity getById(String id) {
        SysLog sysLog = sysLogService.getById(id);
        return ResponseEntity.ok(ApiResult.ok(sysLog));
    }

    /**
     * 删除日志信息
     */
    @GetMapping("/removeSyslog")
    @PreAuthorize("hasAuthority('logs:del')")
    public ResponseEntity removeSyslog(String value, String exception) {

        long l = sysLogService.deleteSyslogByValueAndException(value, exception);

        return ResponseEntity.ok(ApiResult.ok(l));
    }

    /**
     * 导出日志信息
     */
    @PostMapping("/download")
    @PreAuthorize("hasAuthority('logs:dow')")
    public ResponseEntity<byte[]> download(SysLog sysLog, HttpServletResponse response) {

        QueryWrapper<SysLog> queryWrapper = new QueryWrapper<>();

        queryWrapper.select("id,remote_addr,http_method,http_method,http_path,access_time,cost," +
                "user_agent,username,java_method_name,IF(exception IS null,'正常','异常') AS 'exception'");

        queryWrapper.like(StringUtils.hasText(sysLog.getRemoteAddr()), "remote_addr", sysLog.getRemoteAddr())
                .like(StringUtils.hasText(sysLog.getHttpPath()), "http_path", sysLog.getHttpPath())
                .eq(StringUtils.hasText(sysLog.getHttpMethod()), "http_method", sysLog.getHttpMethod())
                .like(StringUtils.hasText(sysLog.getUsername()), "username", sysLog.getUsername())
                .like(StringUtils.hasText(sysLog.getJavaMethodName()), "java_method_name", sysLog.getJavaMethodName())
                .isNull(StringUtils.hasText(sysLog.getException()) && "1".equals(sysLog.getException()), "exception")
                .isNotNull(StringUtils.hasText(sysLog.getException()) && "0".equals(sysLog.getException()), "exception")
        ;

        if (sysLog.getDate() != null) {
            List<String> list = Arrays.asList(sysLog.getDate());
            queryWrapper.between("date(access_time)", list.get(0), list.get(1));
        }

        queryWrapper.orderByDesc("access_time");

        List<SysLog> list = sysLogService.download(queryWrapper);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        EasyExcel.write(outputStream, SysLog.class).sheet("访问日志").doWrite(list);
        byte[] bytes = outputStream.toByteArray();
        response.addHeader("Content-Length", "" + bytes.length);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        return ResponseEntity.ok(bytes);
    }

}
